package pl.pkolodziej.platform.controller.user;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import pl.pkolodziej.platform.service.mail.MailService;
import pl.pkolodziej.platform.service.schedule.ScheduleService;
import pl.pkolodziej.platform.service.user.UserService;
import pl.pkolodziej.platform.vo.course.UserCourseInfo;
import pl.pkolodziej.platform.vo.schedule.Schedule;
import pl.pkolodziej.platform.vo.user.PasswordChange;
import pl.pkolodziej.platform.vo.user.User;
import pl.pkolodziej.platform.vo.user.UserInfo;

@Controller
@RequestMapping(value = "/user")
public class UserController {

	@Autowired
	public UserService userService;

	@Autowired
	public MailService mailService;
	
	@Autowired
	public ScheduleService scheduleService;

	@RequestMapping(value = "/info")
	public String showUserInfo(Map<String, Object> map) {
		User u = new User();
		u.setUsername(SecurityContextHolder.getContext().getAuthentication().getName());
		map.put("userInfo", userService.getUserInfo(u));
		return "user/info";
	}

	@RequestMapping(value = "/update", method = RequestMethod.GET)
	public String editUserInfo(Map<String, Object> map) {
		User u = new User();
		u.setUsername(SecurityContextHolder.getContext().getAuthentication().getName());
		map.put("userInfo", userService.getUserInfo(u));
		return "redirect:/course/list";
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String updateUser(@ModelAttribute("userInfo") UserInfo userInfo,
			BindingResult result, Map<String, Object> map) {
		User u = new User();
		u.setUsername(SecurityContextHolder.getContext().getAuthentication()
				.getName());
		map.put("userInfo", userInfo);
		map.put("user", u);
		try {
			userService.updateUserInfo(userInfo);
		} catch (Exception e) {
			return "redirect:/user/info?edit=1&error=" + e.getLocalizedMessage();
		}
		return "redirect:/course/list";
	}
	
	@RequestMapping(value = "/updatebirthdate", method = RequestMethod.POST)
	public String updateBirthDate(@ModelAttribute("userInfo") UserInfo ui,
			BindingResult result, Map<String, Object> map) {
		User u = new User();
		u.setUsername(SecurityContextHolder.getContext().getAuthentication().getName());
		UserInfo userInfo = userService.getUserInfo(u);
		userInfo.setBirthdate(ui.getBirthdate());
		map.put("userInfo", userInfo);
		map.put("user", u);
		try {
			userService.updateUserInfo(userInfo);
		} catch (Exception e) {
			return "redirect:/user/info?edit=1&error=" + e.getLocalizedMessage();
		}
		
		List<UserCourseInfo> uciList = new ArrayList<UserCourseInfo>();
		for (Object object : userInfo.getUserCourseInfo().toArray()) {
			UserCourseInfo uci = (UserCourseInfo) object;
			uci.setPagesProgress((uci.getPages()*100)/uci.getCourse().getPages());
			uci.setStartTestProgress((uci.getStarttest()*100)/uci.getCourse().getStartTestMaxScore());
			uci.setEndTestProgress((uci.getEndtest()*100)/uci.getCourse().getEndTestMaxScore());
			uciList.add(uci);
		}
		map.put("userCourseInfoList",uciList);
		return "redirect:/course/list";
	}

	@RequestMapping(value = "/changePassword", method = RequestMethod.GET)
	public String changePassword(Map<String, Object> map) {
		PasswordChange pc = new PasswordChange();
		map.put("password", pc);
		return "user/password";
	}

	@RequestMapping(value = "/changePassword", method = RequestMethod.POST)
	public String updatePassword(@ModelAttribute("password") PasswordChange pc,
			BindingResult result, Map<String, Object> map) {
		User u = new User();
		u.setUsername(SecurityContextHolder.getContext().getAuthentication().getName());
		if (!userService.getUserPassword(u.getUsername()).getPassword().equals(pc.getOldPassword()))
			return "redirect:/user/changePassword?oldPasswordFaild=1";
		if (pc.getNewPassword().length() == 0 || !pc.getNewPassword().equals(pc.getRePassword()))
			return "redirect:/user/changePassword?newPasswordFaild=1";

		u.setPassword(pc.getNewPassword());
		u.setEnabled(true);
		try {
			userService.updateUser(u);
			mailService.sendNewPassword(u);
		} catch (Exception e) {
			return "redirect:/user/changePassword?error=" + e.getLocalizedMessage();
		}
		return "redirect:/user/changePassword?save=1";
	}


	@RequestMapping(value = "/listAll")
	public String listContacts(Map<String, Object> map) {
		map.put("usersInfoList", userService.getUsersInfo());
		return "user/list";
	}
	
	@RequestMapping(value = "/schedule")
	public String listSchedule(Map<String, Object> map) {
		map.put("usersInfoList", userService.getUsersInfo());
		return "user/schedule";
	}
	
	private String username;
	List<Schedule> list;
	@RequestMapping(value="/schedule/{username}")
	public String scheduleUser(@PathVariable("username") String username, Map<String, Object> map){
		this.username = username;
		list = scheduleService.listSchedule();
		int i = 0;
		for (Schedule s : list){
			if(s.getUsername().indexOf(username)>-1){
				i++;;
				map.put("schedule"+i, s);
			}
		}
		return "user/scheduleUser";
	}
	
	@RequestMapping(value="/scheduleUpdate")
	public String scheduleUser(@ModelAttribute("userInfo") Schedule schedule, Map<String, Object> map){
		scheduleService.updateSchedule(schedule);
		int i = 0;
		for (Schedule s : list){
			if(s.getUsername().indexOf(username)>-1){
				i++;
				map.put("schedule"+i, s);
			}
		}
		return "user/scheduleUser";
	}

	@RequestMapping(value = "/checkUser/{key}")
	public String checkUser(@PathVariable("key") String key) {
		try {
			userService.verifyUser(key);
		} catch (Exception e) {
			e.printStackTrace();
			return "redirect:/login?verify=0";
		}
		return "redirect:/login?verify=1";
	}


}
